extends Node

var cell_size:int = 16

var reset:bool = true
var random_rect:Rect2
var sand_rect_f : Rect2
var sand_rect_i : Rect2i

var cells:PackedInt32Array = []

var sub_view:SubViewport
var player_0_shape:SubViewShapeParent
var player_1_shape:SubViewShapeParent
var valve:Valve
func add_rect(p_rect):
	if reset:
		reset = false
		sand_rect_f = p_rect
	else:
		sand_rect_f = sand_rect_f.merge(p_rect)
	sand_rect_i = Rect2i(sand_rect_f.grow(cell_size))

func clear():
	cells.clear()
	reset = true

func build_cells():
	var cell_count = (sand_rect_i.size.x / cell_size) * (sand_rect_i.size.y / cell_size)
	cells.clear()
	cells.resize(cell_count)
	cells.fill(1)
	RenderingServer.global_shader_parameter_set("sand_begin",sand_rect_f.position)


func dig_cells(p_cells:Array[Vector2]):
	for i in p_cells:
		var pos:Vector2i =  Vector2i(i) - sand_rect_i.position
		var p_id :int = pos.x/16+pos.y*sand_rect_i.size.x/16
		cells[p_id] = 0

func walk_cells(p_cells:Array[Vector2]):
	var ret:int = 0
	for i in p_cells:
		var pos:Vector2i =  Vector2i(i) - sand_rect_i.position
		var p_id :int = pos.x/16+pos.y*sand_rect_i.size.x/16
		ret += cells[p_id]
	return ret

func get_random_point():
	var x = randf_range(0,random_rect.size.x)
	var y = randf_range(0,random_rect.size.y)
	var ret:Vector2 = random_rect.position
	return ret+Vector2(x,y)
